package hypernexusApp

import (
	"fmt"

	"github.com/TarsCloud/TarsGo/tars"
	"github.com/TarsCloud/TarsGo/tars/util/conf"
	hypernexusInterface "github.com/wzh200x/hyperNexus/hyperNexusInterface"
	hypernexussystem "github.com/wzh200x/hyperNexus/hyperNexusSystem"
)

type HyperNexusApp struct {
	server           hypernexusInterface.IHyperNexusServer
	Comm             *tars.Communicator
	ProjectName      string
	ObjectPoolSystem *hypernexussystem.ObjectPoolSystem // 对象池系统
	AppConf          *conf.Conf
}

func (app *HyperNexusApp) Start() error {
	// 打印框架英语文字log
	fmt.Println(`
  _                           _   _                     
 | |__  _   _ _ __   ___ _ __| \ | | _____  ___   _ ___ 
 | '_ \| | | | '_ \ / _ \ '__|  \| |/ _ \ \/ / | | / __|
 | | | | |_| | |_) |  __/ |  | |\  |  __/>  <| |_| \__ \
 |_| |_|\__, | .__/ \___|_|  |_| \_|\___/_/\_\\__,_|___/
        |___/|_|                                        
	`)
	fmt.Println(app.server.Info())
	tars.AddConfig("server.conf")
	cfg := tars.GetServerConfig().BasePath + "server.conf"
	var err error
	app.AppConf, err = conf.NewConf(cfg)
	if err != nil {
		fmt.Printf("Server Conf Load Failed, err: %v", err)
		return err
	}
	app.ProjectName = tars.GetServerConfig().App
	app.Comm = tars.NewCommunicator()

	// 初始化对象池系统
	if app.ObjectPoolSystem == nil {
		app.ObjectPoolSystem = hypernexussystem.NewObjectPoolSystem()
	}

	err = app.server.Init(app.Comm, app.AppConf)
	if err != nil {
		return err
	}
	err = app.server.InitFinish()
	if err != nil {
		return err
	}
	fmt.Printf("%s start runing...\n", app.server.Name())
	tars.Run()
	defer app.Stop()
	return nil
}

func (app *HyperNexusApp) Stop() {
	// 关闭对象池系统
	if app.ObjectPoolSystem != nil {
		app.ObjectPoolSystem.Shutdown()
	}
	app.server.Stop()
}

func (app *HyperNexusApp) GetServer() hypernexusInterface.IHyperNexusServer {
	return app.server
}

// GetObjectPoolSystem 获取对象池系统
func (app *HyperNexusApp) GetObjectPoolSystem() *hypernexussystem.ObjectPoolSystem {
	return app.ObjectPoolSystem
}

func NewHyperNexusApp(server hypernexusInterface.IHyperNexusServer) *HyperNexusApp {
	GHyperNexusApp = &HyperNexusApp{
		server:           server,
		ObjectPoolSystem: hypernexussystem.NewObjectPoolSystem(),
	}
	return GHyperNexusApp
}

var GHyperNexusApp *HyperNexusApp = nil
